package cn.xspace.library.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.xspace.android.xafcommon.util.LogUtil;

import java.util.ArrayList;
import java.util.List;

import cn.xspace.library.R;
import cn.xspace.library.bean.OrgDeptUserBean;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.view.tree.bean.Node;
import cn.xspace.library.view.tree.bean.TreeHelper;
import rx.Observable;
import rx.Subscriber;


/**
 * @param <T>
 * @author zhy
 */
public class TreeRecycleViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public static final int ITEM_PARENT_LAYOUT = 0;
    public static final int ITEM_SUB_LAYOUT = 1;
    private static final String TAG = "TreeListViewAdapter";
    protected Context mContext;
    private boolean isShowCheck;
    private boolean isShowAdd;
    /**
     * 存储所有可见的Node
     */
    protected List<Node> mNodes;
    protected String user_id;
    protected LayoutInflater mInflater;
    /**
     * 存储所有的Node
     */
    protected List<Node> mAllNodes;
    protected boolean hasHeader;
    /**
     * 点击的回调接口
     */
    protected OnTreeNodeClickListener onTreeNodeClickListener;

    public void setChangeIcon(boolean changeIcon) {
        isChangeIcon = changeIcon;
    }

    private boolean isChangeIcon = false;


    /**
     * @param context
     * @param datas
     * @param defaultExpandLevel 默认展开几级树
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public TreeRecycleViewAdapter(Context context, List<OrgDeptUserBean> datas, int defaultExpandLevel, boolean
            isShowAdd, boolean isShowCheck, boolean hasheader)
            throws IllegalArgumentException, IllegalAccessException {
        mContext = context;
        user_id = MyInfoUtil.getMyUserid(mContext);
        this.hasHeader = hasheader;
        this.isShowCheck = isShowCheck;
        this.isShowAdd = isShowAdd;
//        LogUtil.d(TAG, "TreeListViewAdapter");
        mContext = context;
        /**
         * 对所有的Node进行排序
         */
        mAllNodes = TreeHelper.getSortedNodes(datas, defaultExpandLevel);
        /**
         * 过滤出可见的Node
         */
        mNodes = TreeHelper.filterVisibleNode(mAllNodes);
        mInflater = LayoutInflater.from(context);
        /**
         * 设置节点点击时，可以展开以及关闭；并且将ItemClick事件继续往外公布
         */
//        dataControl(mTree);

    }

    public void defaultOpentStatus() {
        for (Node mNode : mAllNodes) {
            if (MyInfoUtil.getUserOrgId().equals(mNode.getId())) {
                //用户本机构默认实际展开的
                mNode.setExpand(true);
                break;
            }
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View convertView = null;
        switch (viewType) {
            case ITEM_PARENT_LAYOUT:
                convertView = mInflater.inflate(R.layout.list_item_parent_org, parent, false);
                convertView.setClickable(true);
                AddressbookViewHolder holder = new AddressbookViewHolder(convertView);
                if (isChangeIcon) {
                    holder.setChangeIcon(true);
                }
                return holder;
            case ITEM_SUB_LAYOUT:
                convertView = mInflater.inflate(R.layout.list_item_org_user_grey, parent, false);
                convertView.setClickable(true);
                ChildAddressbookViewHolder holder1 = new ChildAddressbookViewHolder(convertView, mContext, isShowCheck);
                return holder1;
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        final Node node = mNodes.get(position);
        ((SubViewHolder<Node>) holder).bindHolder(node);
        final View view = ((SubViewHolder<Node>) holder).convertView;
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onTreeNodeClickListener != null) {
                    if (iOrgUserCheckListener != null) {
                        View checkbox = view.findViewById(R.id.check_select);
                        if (checkbox != null && checkbox instanceof CheckBox) {
                            boolean state = ((CheckBox) checkbox).isChecked();
                            Node node = mNodes.get(position);
                            OrgDeptUserBean bean = (OrgDeptUserBean) node.getObject();
                            if (user_id.equals(bean.user_id)) {
                                return;
                            }
                            if (!bean.isCheckBoxEnable)
                                return;
                            ((CheckBox) checkbox).setChecked(!state);

                            iOrgUserCheckListener.orgUserCheck(position, bean, !state);
                        } else {
                            LogUtil.d("找不到checkbox");
                        }
                    }
                    onTreeNodeClickListener.onClick(mNodes.get(position), position, false);
                }
            }
        });

        final CheckBox checkbox = (CheckBox) view.findViewById(R.id.check_select);

        if (checkbox != null) {
            checkbox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (iOrgUserCheckListener != null) {
                        Node node = mNodes.get(position);
                        OrgDeptUserBean bean = (OrgDeptUserBean) node.getObject();
                        iOrgUserCheckListener.orgUserCheck(position, bean, ((CheckBox) v).isChecked());
                    }
                }
            });

            final RelativeLayout rlRight = (RelativeLayout) view.findViewById(R.id.rl_org_right);
            if (rlRight != null) {
                rlRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (iParentClickListener != null) {
                            Node node = mNodes.get(position);
                            OrgDeptUserBean bean = (OrgDeptUserBean) node.getObject();
                            iParentClickListener.onRightClick(bean, node, position, rlRight);
                        }
                    }
                });
            }

//            checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//                                                    @Override
//                                                    public void onCheckedChanged(CompoundButton buttonView, boolean
// isChecked) {
//                                                        if (iOrgUserCheckListener != null) {
//                                                            Node node = mNodes.get(position);
//                                                            OrgDeptUserBean bean = (OrgDeptUserBean) node.getObject();
//                                                            if (user_id.equals(bean.user_id)) {
//                                                                return;
//                                                            }
//                                                            if (!bean.isCheckBoxEnable)
//                                                                return;
//                                                            iOrgUserCheckListener.orgUserCheck(position, bean,
// isChecked);
//                                                        }
//                                                    }
//                                                }
//            );
        }
//            checkbox.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    L.v("checkbox.isSelected " + checkbox.isSelected());
//                    if (onTreeNodeClickListener != null) {
//                        if (iOrgUserCheckListener != null) {
//                            Node node = mNodes.get(position);
//                            OrgDeptUserBean bean = (OrgDeptUserBean) node.getObject();
//                            if (user_id.equals(bean.user_id)) {
//                                return;
//                            }
//                            if (!bean.isCheckBoxEnable)
//                                return;
//                            iOrgUserCheckListener.orgUserCheck(position, bean, !checkbox.isSelected());
//                        }
//                        onTreeNodeClickListener.onClick(mNodes.get(position), position, false);
//                    }
//                }
//            });


    }

    @Override
    public int getItemViewType(int position) {
        OrgDeptUserBean bean = (OrgDeptUserBean) mNodes.get(position).getObject();
//        LogUtil.d(TAG, "bean name >>" + bean.dept_name + "bean postion " + position + " leaf >>" + bean.isLeaf);
        if (!bean.isLeaf) {
            return ITEM_PARENT_LAYOUT;
        } else {
            return ITEM_SUB_LAYOUT;
        }
    }

    @Override
    public int getItemCount() {
        return mNodes.size();
    }


    public interface OnTreeNodeClickListener {
        void onClick(Node node, int position, boolean isImg);
    }

    public void setOnTreeNodeClickListener(OnTreeNodeClickListener onTreeNodeClickListener) {
        this.onTreeNodeClickListener = onTreeNodeClickListener;
    }

    /**
     * 方法描述 :重新初始化数据
     *
     * @param datas
     * @param defaultExpandLevel
     */
    public void setData(List<OrgDeptUserBean> datas, int defaultExpandLevel) {
        try {

            mAllNodes = TreeHelper.getSortedNodes(datas, defaultExpandLevel);
            /**
             * 过滤出可见的Node
             */
            mNodes = TreeHelper.filterVisibleNode(mAllNodes);

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public Observable setDataRx(final List<OrgDeptUserBean> datas, final int defaultExpandLevel) {
        return Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                try {
                    mAllNodes = TreeHelper.getSortedNodes(datas, defaultExpandLevel);
                    /**
                     * 过滤出可见的Node
                     */
                    mNodes = TreeHelper.filterVisibleNode(mAllNodes);
                    subscriber.onNext("ok");

                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    /**
     * 方法描述 :重新初始化数据
     *
     * @param datas
     * @param defaultExpandLevel
     */
    public void setDataSaveState(List<OrgDeptUserBean> datas, int defaultExpandLevel) {
        try {
            TreeHelper.setNodes(mAllNodes);
            mAllNodes = TreeHelper.getSortedNodes(datas, defaultExpandLevel);
            /**
             * 过滤出可见的Node
             */
            mNodes = TreeHelper.filterVisibleNode(mAllNodes);

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }


    /**
     * 相应ListView的点击事件 展开或关闭某节点
     *
     * @param mTree
     */
    public void oit(int position) {
        expandOrCollapse(position);
    }

    public void oit(int position, boolean isImg) {

        if (hasHeader) {
            if (onTreeNodeClickListener != null) {
                Node node = null;
                if (position > 0) {
                    expandOrCollapse(position - 1);
                    node = mNodes.get(position - 1);
                    onTreeNodeClickListener.onClick(node, position, isImg);
                }
            }
        } else {
            expandOrCollapse(position);
            if (onTreeNodeClickListener != null) {
                onTreeNodeClickListener.onClick(mNodes.get(position), position, isImg);
            }
        }
    }

    /**
     * 展开或者关闭节点
     *
     * @param position
     */
    public void expandOrCollapse(int position) {
        Node n = mNodes.get(position);
        LogUtil.d(TAG, " n " + n.getName() + " n.isExpand() " + n.isExpand());
        LogUtil.d(TAG, "mNodes size begin" + mNodes.size());
        if (n != null) {// 排除传入参数错误异常
            if (!n.isLeaf()) {
                n.setExpand(!n.isExpand());
//                mNodes = TreeHelper.filterVisibleNode(mAllNodes, n);
                mNodes = TreeHelper.filterVisibleNode(mAllNodes);
                LogUtil.d(TAG, "mNodes size end" + mNodes.size());
                notifyDataSetChanged();// 刷新视图
            }
        }
    }

    public Observable expandOrCollapseRx(final int position) {
        return Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                Node n = mNodes.get(position);
                LogUtil.d(TAG, " n " + n.getName() + " n.isExpand() " + n.isExpand());
                LogUtil.d(TAG, "mNodes size begin" + mNodes.size());
                if (n != null) {// 排除传入参数错误异常
                    if (!n.isLeaf()) {
                        n.setExpand(!n.isExpand());
//                mNodes = TreeHelper.filterVisibleNode(mAllNodes, n);
                        mNodes = TreeHelper.filterVisibleNode(mAllNodes);
                        LogUtil.d(TAG, "mNodes size end" + mNodes.size());

                    }
                }
                subscriber.onNext("ok");
            }
        });
    }


//	/**
//	 *
//	 * 方法描述 : 该方法实现的功能描述
//	 * @param position
//	 */
//	public void collapseAllButPost(Node node) {
//		for (Node n : mNodes) {
//			if (n != null) {
//				if (!n.isLeaf()) {
//					if (node.getId() != null && node.getId().equals(n.getId())) {
//						n.setExpand(true);
//					} else {
//						n.setExpand(false);
//					}
//				}
//			}
//		}
//		mNodes = TreeHelper.filterVisibleNode(mAllNodes);
//		notifyDataSetChanged();// 刷新视图
//
//	}

    private void collapseAllParent() {
        for (Node n : mNodes) {
            if (n != null) {
                if (!n.isLeaf()) {
                    n.setExpand(false);
                }
            }
        }
    }

    /**
     * 方法描述 : 得到目前的所有打开并且有子元素的的节点列表
     *
     * @return
     */
    public List<String> getLastNodeId() {
        List<String> resultList = new ArrayList<String>();
        for (Node n : mNodes) {
            if (n.isExpand() && n.getChildren().size() > 0) {
                resultList.add(n.getId());
            }
        }
        return resultList;
    }

    /**
     * 方法描述 : 打开指定id列表
     *
     * @param idList
     */
    public void collapseNodeIdList(List<String> idList) {
//        collapseAllParent();
//        List<Node> resultList = new ArrayList<>();

        for (String id : idList) {
            for (Node n : mNodes) {
                if (id.equals(n.getId()) && !n.isLeaf()) {
                    n.setExpand(true);
                    break;
                }
            }
        }
//        for (Node n : mNodes) {
//            if (n != null) {
//                if (!n.isLeaf()) {
//                    for (String id : idList) {
//                        if (id.equals(n.getId())) {
//                            n.setExpand(true);
////                            resultList.addAll(TreeHelper.filterVisibleNode(mAllNodes, n));
//                            break;
//                        }
//                    }
//                }
//            }
//        }
        mNodes = TreeHelper.filterVisibleNode(mAllNodes);
//        mNodes = resultList;
        notifyDataSetChanged();
    }


    /**
     * 创建ViewHolder
     */
//    @Override
//    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
//
//        View convertView = null;
//        switch (viewType) {
//            case ITEM_PARENT_LAYOUT:
//                convertView = mInflater.inflate(R.layout.list_item_parent_org, viewGroup, false);
//                return new AddressbookViewHolder(convertView);
//                break;
//            case ITEM_SUB_LAYOUT:
//                convertView = mInflater.inflate(R.layout.list_item_org_user_grey, viewGroup, false);
//                return new ChildAddressbookViewHolder(convertView,);
//                break;
//        }
//        if (convertView == null) {
//            return null;
//        }
//
//    }
//
//    /**
//     * 设置值
//     */
//
//    @Override
//    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int position) {
//        Node node = mNodes.get(position);
//        ((AddressbookViewHolder) viewHolder).bindHolder(node);
//    }
//
//    @Override
//    public int getItemViewType(int position) {
//        OrgDeptUserBean bean = (OrgDeptUserBean) mNodes.get(position).getObject();
////        LogUtil.d(TAG, "bean name >>" + bean.dept_name + "bean postion " + position + " leaf >>" + bean.isLeaf);
//        if (!bean.isLeaf) {
//            return ITEM_PARENT_LAYOUT;
//        } else {
//            return ITEM_SUB_LAYOUT;
//        }
//
//    }


//    @Override
//    public View getView(int position, View convertView, ViewGroup parent) {
//        try {
//            LogUtil.d(TAG, "public View getView(int position, View convertView, ViewGroup parent) {");
//            Node node = mNodes.get(position);
//            convertView = getConvertView(node, position, convertView, parent);
//            // 设置内边距
//            LogUtil.d(TAG, " level >>" + node.getLevel() + " node name" + node.getName());
//            int padleft = getPadLeft(node.getLevel());
//            ViewGroup vg = (ViewGroup) convertView;
//            View oneView = vg.getChildAt(0);
//            LogUtil.d(TAG, "paddingLeft>>" + padleft);
//            LogUtil.d(TAG, "oneView>>>" + oneView.getId());
//            if (oneView instanceof RelativeLayout) {
//                LogUtil.d(TAG, "RelativeLayout");
//            } else if (oneView instanceof ImageView) {
//                LogUtil.d(TAG, "ImageView");
//            }
//            if (oneView != null) {
////            oneView.setPadding(padleft, 0, 10, 0);
//                int top = convertView.getPaddingTop();
//                int bottom = convertView.getPaddingBottom();
////            oneView.setPadding(padleft + 10, top, 20, bottom);
//                convertView.setPadding(padleft + 10, top, 20, bottom);
//            } else {
//                convertView.setPadding(padleft, 3, 3, 3);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return convertView;
//    }

//    public abstract View getConvertView(Node node, int position, View convertView, ViewGroup parent);
    private void viewOnclick(View v, final Node node) {
        v.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, node.getName(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private IOrgUserCheckListener iOrgUserCheckListener;


    public void setiOrgUserCheckListener(IOrgUserCheckListener iOrgUserCheckListener) {
        this.iOrgUserCheckListener = iOrgUserCheckListener;
    }

    private IParentClickListener iParentClickListener;

    public void setiParentClickListener(IParentClickListener iParentClickListener) {
        this.iParentClickListener = iParentClickListener;
    }


    public interface IOrgUserCheckListener {
        void orgUserCheck(int postion, OrgDeptUserBean bean, boolean isChecked);
    }

    public interface IItemClickListener {
        void itemClick(int postion, OrgDeptUserBean bean, boolean isChecked);
    }

    public interface IParentClickListener {
        void onRightClick(OrgDeptUserBean bean, Node node, int position, RelativeLayout iconRight);
    }


}
